Classes

Objects and Classes

An object exists in memory and performs a specific task

Class: Code that describes a particular type of object.

Remember:

Creating a Typical Object:

  1. Declare reference variable
  2. Create object in memory and assign memory address to reference variable.

Writing a Class

Suppose we want a Rectangle object to store length and width (fields)

UML Diagram

Unified Modeling Language (UML): Set of standard diagrams for graphically depicting object-oriented systems.

General Structure:

ClassNameFieldsMethods()

For our Rectangle example:

Rectanglelength : doublewidth : doublesetLength(l : double) : voidsetWidth(w : double) : voidgetLength() : doublegetWidth() : doublegetArea() : double

Access Specifiers

Access Specifier: Java keyword that indicates how a field or method can be accessed.

public class Rectangle
{
    // These variables can only be accessed by methods in the class
    private double length;
    private double width;

    // == Mutators ==

    // Note how this isn't static b/c we want each instance to have their own setLength method
    // - We only use static for methods that don't depend on specific instances
    public void setLength (double l) {
        length = l;
    }
    public void setWidth (double w) {
        width = w;
    }

    // == Accessors ==

    public double getLength () {
        return length;
    }
    public double getWidth () {
        return width;
    }

    // == Other ==

    public double getArea()
    {
        return length * width;
    }
}

Accessors and Mutators (Setters and Getters)

Because of data hiding, we interact with fields with:

Data Hiding

Note: Important concept in OOP!

Stale Data

Data that requires calculation has the potential to become stale.

Class Layout Conventions

Common layout:

Instance Fields and Methods

Instance Methods: Methods that are not declared with the static keyword. Instance Fields: Fields that each instanced object has their own version of.

Note: Both require an object to be created to be used!

Using Same Variable Names in Setters

Suppose the following setter:

public Rectangle(double l, double w) {
    length = l;
    width = w;
}

We can use the this keyword to refer to instance fields with the same names as the arguments:

public Rectangle(double length, double width) {
    this.length = length;
    this.width = width;
}

Constructors

Constructor: Method that’s automatically called when an object is created.

Constructors in UML

Constructors don’t have their return type listed.

For our Rectangle example:

Rectanglelength : doublewidth : doubleRectangle(len:double, w:double)setLength(l : double) : voidsetWidth(w : double) : voidgetLength() : doublegetWidth() : doublegetArea() : double

Uninitialized Local Reference Variables

We can create reference variables without initializing them.

e.g.,

Rectangle box;

If you try to use an uninitialized local reference variable a compiler error will occur.

The Default Constructor

If you don’t write a constructor, Java will provide a default constructor that:

Note: The default constructor exists only when you don’t write a constructor and takes no parameters.

No-Arg Constructor

No-Arg Constructor: A constructor that doesn’t accept arguments.

Note: A No-Arg constructor \ne the default constructor.

Passing Objects as Arguments

When passing an argument, the object;s memory address is what’s actually passed into the parameter variable.

Overloading Methods and Constructors

Method Overloading: When two or more methods have the same name but different argument lists.

e.g.,

public Rectangle(double length, double width) {
    this.length = length;
    this.width = width;
}
public Rectangle() {
    this.length = 7;
    this.width = 7;
}

Method Signature and Binding

Method Signature:

For example, here are the method signatures of the Rectangle examples in the previous section:

Rectangle(double,double)
Rectangle()

Binding: The process of bathing a method call with the correct method

BankAccount Example

Here’s a class that demonstrates overloaded methods and constructors.

BankAccountbalance : doubleBankAccount()BankAccount(startBalance:double)BankAccount(str:String)deposit(amount:double):voiddeposit(str:String):voidwithdraw(amount:double):voidwidhdraw(str:String):voidsetBalance(b:double):voidsetBalance(str:String):voidgetBalance():double

Scope of Instance Fields

Variables declared as instance fields can be accessed by any instance method in the same class as the field.

Shadowing

A parameter variable, in effect, is a local variable.

Packages and import Statements

Package: Group of related classes.

Some Java Standard Packages

The toString Method

Rectangle box = new Rectangle();

// Explicitly calling toString()
System.out.println(box1.toString());

// Implicitly calling toString()
System.out.println(box1);

Static Class Members

Static fields and static methods don’t belong to a single instance of a class.

To invoke a static method or field, the class name is used instead of an instance name, like so:

// Class Name: Math
// Static Method: sqrt()
double x = Math.sqrt(25.0);

Static Fields

To declare a static field, put static keyword between access specifier (private/public) and field type (e.g., int, double), like so:

private static int instanceCount = 0;

Static Methods

Static methods can be declared by putting static between access specifier and return type, like so:

public static double milesToKilos(double miles)

The equals Method

Like toString, all objects have a default equals method that compares memory addresses of the objects like the == operator.

Methods that Copy Objects

Two ways to copy an object:

  1. Reference-Only Copy: Copy memory address of object into reference variable.
// Reference-Only Copy
Stock company1 = new Stock("XYZ", 9.62);
Stock company2 = company1;
  1. Deep Copy: Copy values into a new instance of the class.

Copy Constructors

A constructor that accepts an existing object of the same class and clones it.

Example:

// Copy Constructor
public Stock(Stock orig)
{
    this.symbol = orig.getSymbol();
    this.sharePrice = orig.getSharePrice();
}
// Deep Copy
Stock company1 = new Stock("XYZ", 9.62);
Stock company2 = new Stock(company1):

Null References

Null Reference: Reference variable that points to nothing.

if (x != nul) { /* (do something with x) */ }

this Reference

this Reference: Name an object can use to refer to itself.

Garbage Collection

Unused objects should be destroyed to free the memory they consumed.

finalize Method

If an object has a method with the signature—

public void finalize()

—It will run prior to the garbage collector reclaiming its memory. - Remember that we can’t tell when finalize will actually be run, because the garbage collector is a background thread that runs periodically.

Aggregation

Object Aggregation: Making an instance of one class a field in another class.

Example UML Diagram:

BankAccountbalance : doubleassignedManager : ManagerpreferredBranch : BranchBankAccount()BankAccount(startBalance:double)BankAccount(str:String)deposit(amount:double):voiddeposit(str:String):voidwithdraw(amount:double):voidwidhdraw(str:String):voidsetBalance(b:double):voidsetBalance(str:String):voidgetBalance():doubleManagerlastName : StringfirstName : Stringphone : StringManager(fullName:String,phone:String):voidgetName():StringgetPhone():StringBranchlocation : StringBranch(location : String):voidgetLocation():String